// pages/login/index.js
const util = require('../../utils/util.js')
import {generateKeys} from '../../utils/RSA_AES.js'
import {Base64Encrypt,Base64Decrypt,Decrypt,EncryptAES,SHA256,RSA_encrypt,RSA} from '../../utils/crypto_RSA_AES.js'

const HttpAjax = getApp().getHttpData
// let cook;
var app = getApp().globalData; // 取得全局App.globalData       app.url可获取得url


let timeout=0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    phone: '',
    disBol: false, //是否获取验证码倒计时中
    validtxt: '获取验证码',
    validval: '',
    IsPhone_vali: false, //是否获取验证码了？
    loadingBol: true,
    disBol1: false,
    isROOT: false,
    explain:false,
    agree:false,
    logbool:true,
    RsaKey:null
  },
  onGetUserInfo: function (e) {//授权
    if (!this.logged && e.detail.userInfo) {
      app.userInfo = e.detail.userInfo;
      this.setData({
        isROOT: false
      })
      this.toFcard()
      // wx.switchTab({
      //   url: '/pages/basics/home/home',
      // })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let RsaKey={}
    let ms = generateKeys();
    RsaKey.public=ms[0];
    RsaKey.private=ms[1];
    this.setData({
      RsaKey:RsaKey
    })
    this.toFcard()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },
  toFcard() {
    let that = this;
    // if (wx.getStorageSync('isLogin')==true){
    //   wx.switchTab({
    //     url: '../fcard/index'
    //   })
    // }else{

    // }
    wx.login({
      success: res => {
        app.code = res.code;
        that.setData({
          loadingBol: true,
          logbool:true
        })
        let a = new Date().getTime()
        // console.log(a-timeout)
        // console.log(app.code)
        // return;

        let parma = {
          'code': app.code,
          Loginciphertext:RSA_encrypt().encrypt('')
        }
        HttpAjax(app.url + '/MicroApp/Login',        ///判断是否登录
          parma
        , 'post', app.headerCookie)
          .then(rej => {
            // console.log(rej)
            if(rej.data.result){
              if (rej.data.result == 1) {
                let a = new Date().getTime();
                console.log(a - timeout);
                wx.setStorageSync('isLogin',true)
                wx.setStorageSync('AKey',rej.data.Data.AKey)
                wx.setStorageSync('AIV',rej.data.Data.AIV)
                setTimeout(() => {
                  wx.switchTab({
                    url: '../fcard/index'
                  })
                }, 50);
                console.log(rej)
                // that.setData({
                //   loadingBol: false,
                //   logbool: false
                // })
                app.cardid = rej.data.Data.CardData;
              } else {
                that.setData({
                  loadingBol: false,
                  logbool: false
                })
                console.log("wx.getStorageSync('isLogin')==true",wx.getStorageSync('isLogin')==true)
                wx.setStorageSync('isLogin',false)
                wx.showToast({
                  title: '用户未注册',
                  icon: 'none',
                  duration: 2000
                })
              }
            }else{
              that.setData({
                loadingBol: false,
                logbool: false
              })
              // console.log("wx.getStorageSync('isLogin')==true",wx.getStorageSync('isLogin')==true)
              wx.setStorageSync('isLogin',false)
              wx.showToast({
                title: '用户未注册',
                icon: 'none',
                duration: 2000
              })
            }
          })
          .catch(res => {
            // console.log(res)
            that.setData({
              loadingBol: false,
              logbool: false
            })
            // console.log("wx.getStorageSync('isLogin')==true",wx.getStorageSync('isLogin')==true)
            wx.setStorageSync('isLogin',false)
            if (res.errMsg == 'request:fail ') {
              setTimeout(() => {
                wx.showToast({
                  title: '登录失败！请重试',
                  icon: 'none',
                  duration: 2000
                })
              }, 3000)

            }
            

            // console.log(res)
          })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    timeout = new Date().getTime();
    // that.toFcard();
    // function getAppUser(){
    //   if (app.userInfo == null || app.userInfo == 'undefined') {
    //     // that.setData({
    //     //   isROOT: true
    //     // })
    //     // console.log(app)
    //     // getAppUser();
    //     timeout=setTimeout(getAppUser,10)
    //   }else{
    //     console.log(app);
    //     clearTimeout(timeout)
    //     that.toFcard();
    //   }
    // }
    // wx.getUserInfo({
    //   withCredentials: true,
    //   lang: 'zh',
    //   success: function(res) {
    //     console.log(res);
    //     getAppUser();
    //   },
    //   fail: function(res) {
    //     console.log(res);
        
    //     that.setData({
    //       isROOT: true
    //     })
    //     clearTimeout(timeout)
    //   }
    // })

  },
  showDialog: function () {
    this.dialog.showDialog();
  },
  confirmEvent: function () {
    this.dialog.hideDialog();
  },
  bindGetUserInfo: function () {
    // 用户点击授权后，这里可以做一些登陆操作
    // console.log(app.userInfo)
    this.dialog.showDialog();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  signIn() { //注册按钮
    let that = this;
    if (/^1(3|4|5|7|8)\d{9}$/.test(this.data.phone)) {
      // console.log(/^1(3|4|5|7|8)\d{9}$/.test(this.data.phone))
      // return
      wx.showLoading({
        title: '正在注册'
      });
      this.setData({
        disBol1: true
      })
      wx.login({
        success: res => {
          app.code = res.code
          let parma={
            'MobilePhone': that.data.phone,
            'Code': app.code,
            Loginciphertext:RSA_encrypt().encrypt('')
          }
          HttpAjax( //注册
            app.url + '/MicroApp/Logup', parma,
            'post',
            app.headerCookie
          )
          .then(res => {
            this.setData({
              disBol1: false
            })
            wx.hideLoading()
            if (res.data.result == '1') {
              app.cardid = res.data.Data;
              wx.showToast({
                title: '注册成功',
                icon: 'none',
                duration: 2000
              })
              wx.switchTab({
                url: './../fcard/index'
              })
              wx.setStorageSync('AKey',rej.data.Data.AKey)
              wx.setStorageSync('AIV',rej.data.Data.AIV)
              app.cardid=that.data.phone;
            } else {
              wx.showToast({
                title: res.data.Message,
                icon: 'none',
                duration: 2000
              })
            }
          })
            .catch(res => {
              this.setData({
                disBol1: false
              })
              wx.hideLoading()
              wx.showToast({
                title: '注册失败，请重试',
                icon: 'none',
                duration: 2000
              })
            })
        }
      })
    } else {
      wx.showToast({
        title: '请填写或输入正确的手机号码',
        icon: 'none',
        duration: 2000
      })
    }


  },
  getvalid(e) { //是否授权&&获取验证码按钮
    let that = this;
    if (/^1[3|5|7|8][0-9]\d{4,8}$/.test(this.data.phone)) {
      HttpAjax(app.url + '/MicroApp/VerifyCode', {
        phoneNumber: this.data.phone
      }, 'get')
        .then(res => {
          console.log(app.headerCookie);
          if (res.data.result == 1) {
            wx.showToast({
              title: '验证码发送成功',
              icon: 'none',
              duration: 2000
            })
            //成功倒计时  禁止点击获取验证码按钮
            this.setData({
              validtxt: '(120秒)后重新获取',
              disBol: true,
              IsPhone_vali: true
            })
            let t = 120;
            let timr = setInterval(() => {
              that.setData({
                validtxt: `(${t--}秒)后重新获取`
              })
              if (t == 0) {
                clearInterval(timr);
                this.setData({
                  validtxt: '获取验证码',
                  disBol: false
                })
              }
            }, 1000)
          } else {
            console.log('ceshi:', res)
            wx.showToast({
              title: res.data.Message,
              icon: 'none',
              duration: 2000
            })
          }
        })
        .catch(res => {
          if (res.errMsg == 'request:fail ') {
            wx.showToast({
              title: '请求超时！',
              icon: 'none',
              duration: 2000
            })
          }
        })




    } else {
      wx.showToast({
        title: '请填写或输入正确的手机号码',
        icon: 'none',
        duration: 2000
      })
    }
  },
  bindKeyInput: function (e) { //监控手机号码输入并赋值
    this.setData({
      phone: e.detail.value
    })
    // console.log(this.data.phone)
  },
  getAuthCode(e) { //监控验证码输入并赋值
    this.setData({
      validval: e.detail.value
    })

  },
  bindGetUserInfo: function (e) {
    // console.log(e.detail.userInfo)

  },
  reslogin() {//重新登录
    let that = this;
    let parma = {
      'code': app.code,
      Loginciphertext:RSA_encrypt().encrypt('')
    }
    HttpAjax(app.url + '/MicroApp/Login',       ///判断是否登录
    parma
    , 'post', app.headerCookie)
      .then(rej => {
        console.log(rej)
        // if (rej.data.result == 1) {
        //   setTimeout(() => {
        //     wx.switchTab({
        //       url: '../fcard/index'
        //     })
        //   }, 500);
        //   // console.log(rej)
        //   app.cardid = rej.data.Data;
        // } else {
        //   that.setData({
        //     loadingBol: false
        //   })
        //   wx.showToast({
        //     title: '此号码没注册',
        //     icon: 'none',
        //     duration: 2000
        //   })
        // }
      })
      .catch(res => {
        console.log(app.url + '/MicroApp/Login')
        if (res.errMsg == 'request:fail ') {
          setTimeout(() => {
            wx.showToast({
              title: '登录失败',
              icon: 'none',
              duration: 2000
            })
          }, 3000)

        }
        that.setData({
          loadingBol: false
        })

        // console.log(res)
      })
  },
  Closeminprog(){
    console.log('min')
    wx.navigateBack({
      delta: 1
    })
  },
  explainfun(){
    this.setData({
      explain:!this.data.explain
    })
  },
  checkboxChange(){
    console.log(this.data.agree);
    let a= !this.data.agree;
    console.log(a);
    this.setData({
      agree: a
    })
  },
  loadingBolfun(){
    if(this.data.agree){
      this.setData({
        logbool: true
      })
    }else{
      wx.showToast({
        title: '请同意注册再进行下一步',
        icon: 'none',
        duration: 2000
      })
    }
  }
})